package com.aliyun.messagemgt.application.service.Impl;


import com.aliyun.messagemgt.common.dto.send.MsgMiddleResult;
import com.aliyun.messagemgt.common.dto.send.MsgRecordVO;
import com.aliyun.messagemgt.common.dto.send.Receiver;
import com.aliyun.messagemgt.application.service.FlowControl;
import com.aliyun.messagemgt.application.service.MsgFlowControl;
import com.aliyun.messagemgt.common.enums.PushResultEnum;
import com.aliyun.messagemgt.dto.MsgSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IDEA
 *
 * @author:zhangxingxing 0027012120
 * @date:2019/4/3
 * @time:15:30
 */
@Component
public class MsgFlowControlImpl implements MsgFlowControl {

    @Autowired
    private FlowControl flowControl;

    @Override
    public void flowControl(List<MsgRecordVO> msgRecordVos, MsgSource msgSource) {
        for (MsgRecordVO msgRecordVO : msgRecordVos) {
            List<MsgMiddleResult> results = msgRecordVO.getResults();
            List<Receiver> receivers = msgRecordVO.getReceivers();
            int size = receivers.size();
            int remain = flowControl.inControl(size, msgSource);
            if (remain == -1) {
                return;
            }
            if (remain == 0) {
                MsgMiddleResult msgMiddleResult = new MsgMiddleResult()
                        .setReceivers(receivers)
                        .setPushResultCode(PushResultEnum.FLOW_OVER_LIMIT.getErrorCode())
                        .setPushResultDescription(PushResultEnum.FLOW_OVER_LIMIT.getDescription());
                results.add(msgMiddleResult);
                msgRecordVO.setReceivers(new ArrayList<>());
            } else {
                List<Receiver> validReceivers = new ArrayList<>(receivers.subList(0, remain));
                List<Receiver> invalidReceivers = new ArrayList<>(receivers.subList(remain, size));
                MsgMiddleResult msgMiddleResult = new MsgMiddleResult()
                        .setReceivers(validReceivers)
                        .setPushResultCode(PushResultEnum.FLOW_OVER_LIMIT.getErrorCode())
                        .setPushResultDescription(PushResultEnum.FLOW_OVER_LIMIT.getDescription());
                results.add(msgMiddleResult);
                msgRecordVO.setReceivers(invalidReceivers);
            }
        }
    }
}
